import 'dart:ui';

import 'package:animated_transitions/transition_page_route.dart';
import 'package:animated_transitions/transitions/crt_shutoff_transition.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/view/main/main_page.dart';
import '../../core/index.dart';

/// 设置页面界面
class VamosSettingsInterface extends StatefulWidget {
  const VamosSettingsInterface({super.key});

  @override
  State<VamosSettingsInterface> createState() => _VamosSettingsInterfaceState();
}

class _VamosSettingsInterfaceState extends State<VamosSettingsInterface> {
  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, AppState>(
      converter: (store) => store.state,
      builder: (context, state) {
        final currentUser = state.userState.activeUser;

        if (currentUser == null) {
          return Scaffold(
            body: Center(
              child: Text(
                'Please login to access settings',
                style: TextStyle(color: Colors.white, fontSize: 18.sp),
              ),
            ),
          );
        }

        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: _buildSettingsContent(currentUser),
          ).safeArea(top: false, bottom: false),
        );
      },
    );
  }

  Widget _buildSettingsContent(UserDataEntity currentUser) {
    return Column(
      children: [
        // 顶部导航栏
        _buildTopNavigationBar(),

        // 用户信息区域
        _buildUserInfoSection(currentUser),

        // 设置选项区域
        Expanded(child: _buildSettingsOptions()),

        // 退出登录按钮
        _buildLogoutButton(),

        SizedBox(height: 50.h),
      ],
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 12.h,
        left: 16.w,
        right: 16.w,
        bottom: 12.h,
      ),
      child: Row(
        children: [
          // 返回按钮
          Icon(
            Icons.arrow_back,
            size: 26.w,
            color: Colors.white,
          ).center().inkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text(
                'SETTINGS',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                  fontFamily:
                      GoogleFonts.goblinOne(
                        fontWeight: FontWeight.w700,
                      ).fontFamily,
                ),
              ),
            ),
          ),

          SizedBox(width: 36.w),
        ],
      ),
    );
  }

  /// 构建用户信息区域
  Widget _buildUserInfoSection(UserDataEntity currentUser) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: Column(
        children: [
          // 用户头像
          Container(
            width: 64.w,
            height: 64.w,
            margin: EdgeInsets.all(3.w),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Colors.transparent,
            ),
            child: ClipOval(
              child:
                  currentUser.profileImage.isNotEmpty
                      ? Image.asset(
                        currentUser.profileImage,
                        width: 88.w,
                        height: 88.w,
                        fit: BoxFit.cover,
                      )
                      : Icon(
                        Icons.person,
                        size: 50.w,
                        color: Colors.white,
                      ).center(),
            ),
          ),

          SizedBox(height: 16.h),

          // 用户名
          Text(
            currentUser.displayName,
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.sp,
              fontWeight: FontWeight.w600,
              fontFamily:
                  GoogleFonts.quantico(fontWeight: FontWeight.w600).fontFamily,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建设置选项
  Widget _buildSettingsOptions() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 隐私政策
          _buildSettingsOption(
            title: 'Privacy Policy',
            onTap: () {
              _handlePrivacyPolicyTap();
            },
          ),

          SizedBox(height: 16.h),

          // 服务条款
          _buildSettingsOption(
            title: 'Terms Of Service',
            onTap: () {
              _handleTermsOfServiceTap();
            },
          ),

          SizedBox(height: 16.h),

          // 删除账号
          _buildSettingsOption(
            title: 'Delete Account',
            onTap: () {
              _handleDeleteAccountTap();
            },
          ),
        ],
      ),
    );
  }

  /// 构建单个设置选项
  Widget _buildSettingsOption({
    required String title,
    required VoidCallback onTap,
  }) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(24.r),
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
        child: Container(
          width: double.infinity,
          height: 44.h,
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.2),
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
          ),
          child: Row(
            children: [
              // 左侧内容
              Expanded(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Text(
                    title,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                      fontFamily:
                          GoogleFonts.poppins(
                            fontWeight: FontWeight.w500,
                          ).fontFamily,
                    ),
                  ),
                ),
              ),

              // 右侧箭头
              Padding(
                padding: EdgeInsets.only(right: 20.w),
                child: Icon(
                  Icons.arrow_forward_ios,
                  color: Colors.white.withOpacity(0.7),
                  size: 16.w,
                ),
              ),
            ],
          ),
        ).inkWell(onTap: onTap),
      ),
    );
  }

  /// 构建退出登录按钮
  Widget _buildLogoutButton() {
    return Container(
      margin: EdgeInsets.all(16.w),
      width: double.infinity,
      height: 44.h,
      decoration: BoxDecoration(
        color: const Color(0xFFF7CEBA),
        borderRadius: BorderRadius.circular(41.r),
      ),
      child: Text(
        'LOGOUT',
        style: TextStyle(
          color: Colors.black,
          fontSize: 20.sp,
          fontWeight: FontWeight.w700,
          fontFamily:
              GoogleFonts.protestStrike(fontWeight: FontWeight.w700).fontFamily,
        ),
      ).center().inkWell(
        onTap: () {
          _handleLogoutTap();
        },
      ),
    );
  }

  /// 处理隐私政策点击
  void _handlePrivacyPolicyTap() async {
    try {
      await VamUrl.openPrivacy();
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(
          context,
          message: 'Failed to open Privacy Policy',
        );
      }
    }
  }

  /// 处理服务条款点击
  void _handleTermsOfServiceTap() async {
    try {
      await VamUrl.openTerms();
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(
          context,
          message: 'Failed to open Terms of Service',
        );
      }
    }
  }

  /// 处理删除账号点击
  void _handleDeleteAccountTap() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            backgroundColor: Colors.white.withOpacity(0.9),
            title: Text(
              'Delete Account',
              style: TextStyle(
                color: Colors.black,
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
              ),
            ),
            content: Text(
              'Are you sure you want to delete your account? This action cannot be undone.',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(
                  'Cancel',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w500,
                        ).fontFamily,
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  _confirmDeleteAccount();
                },
                child: Text(
                  'Delete',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                ),
              ),
            ],
          ),
    );
  }

  /// 确认删除账号
  void _confirmDeleteAccount() async {
    try {
      // 显示删除成功提示
      NotificationUtils.showSuccess(
        context,
        message: 'Account deleted successfully',
      );

      // 延迟一下让用户看到提示
      await Future.delayed(Duration(milliseconds: 500));

      // 实际执行退出登录
      final userManager = serviceLocator<ReduxUserManager>();
      userManager.logout();

      if (mounted) {
        Navigator.of(context).pushReplacement(
          TransitionPageRoute(
            builder:
                (context) => StoreProvider<AppState>(
                  store: appStore,
                  child: const VamosMainInterface(),
                ),
            transitionAnimation: CrtShutoffTransition(),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(
          context,
          message: 'Failed to delete account: $e',
        );
      }
    }
  }

  /// 处理退出登录点击
  void _handleLogoutTap() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            backgroundColor: Colors.white.withOpacity(0.9),
            title: Text(
              'Logout',
              style: TextStyle(
                color: Colors.black,
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w600).fontFamily,
              ),
            ),
            content: Text(
              'Are you sure you want to logout?',
              style: TextStyle(
                color: Colors.black,
                fontSize: 14.sp,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(
                  'Cancel',
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w500,
                        ).fontFamily,
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  _performLogout();
                },
                child: Text(
                  'Logout',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                ),
              ),
            ],
          ),
    );
  }

  /// 执行退出登录
  void _performLogout() async {
    try {
      final userManager = serviceLocator<ReduxUserManager>();
      userManager.logout();

      if (mounted) {
        Navigator.of(context).pushReplacement(
          TransitionPageRoute(
            builder:
                (context) => StoreProvider<AppState>(
                  store: appStore,
                  child: const VamosMainInterface(),
                ),
            transitionAnimation: CrtShutoffTransition(),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        NotificationUtils.showError(context, message: 'Failed to logout: $e');
      }
    }
  }
}
